const gulp = require("gulp");
const { src, pipe, dest, parallel, series, watch } = require("gulp");
const less = require("gulp-less");
const minifyCss = require("gulp-clean-css");
const fileRename = require("gulp-rename");
const autoprefixer = require("gulp-autoprefixer");
const babel = require("gulp-babel");
const uglify = require("gulp-uglify");
const htmlmin = require("gulp-htmlmin");
// const imagemin = require("gulp-imagemin");
const del = require("del");
const bs = require("browser-sync");

const style = () => {
  return src("src/assets/style/*.less", { base: "src" })
    .pipe(less())
    .pipe(autoprefixer())
    .pipe(minifyCss())
    .pipe(fileRename({ extname: ".min.css" }))
    .pipe(dest("dist"));
};
const script = () => {
  return src("src/assets/js/*.js", { base: "src" })
    .pipe(babel({ presets: ["babel-preset-env"] }))
    .pipe(fileRename({ extname: ".min.js" }))
    .pipe(uglify())
    .pipe(dest("dist"));
};

const html = () => {
  return src("src/index.html")
    .pipe(
      htmlmin({
        collapseWhitespace: true,
        minifyCSS: true,
        minifyJS: true,
        minifyURLs: true,
      })
    )
    .pipe(dest("dist"));
};

// const image = () => {
//   return src("src/assets/img/**", { base: "assets" })
//     .pipe(imagemin())
//     .pipe(dest("dist"));
// };

const image = () => {
  return src("src/assets/img/**", { base: "src" }).pipe(dest("dist"));
};

const clean = () => {
  return del(["dist"]);
};

const serve = () => {
  watch("src/index.html", html);
  watch("src/assets/js/*.js", script);
  watch("src/assets/style/*.less", style);
  watch("src/assets/img/**", image);
  bs.init({
    notify: false,
    files: "./dist/**",
    server: {
      baseDir: "./dist",
      // 路由映射，将原文件中使用到此路径地址，打包后修改为指定路径
      routes: {
        "/node_modules": "node_modules",
      },
    },
  });
};
const build = series(clean, parallel(style, script, image, html));
const dev = series(build, serve);
module.exports = {
  build,
  dev,
};
